package com.zhenlong01.zhentest.controller;

import com.alibaba.fastjson.JSONObject;
import com.zhenlong01.zhentest.dao.TodoDao;
import com.zhenlong01.zhentest.entity.Todo;
import com.zhenlong01.zhentest.util.AccessTokenUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import java.util.Date;


/**
 * @author Administrator
 * @date 2019-08-22 13:13
 */
@RestController
public class IndexControlelr {
    @Autowired
    TodoDao todoDao;

    @PostMapping("/index")
    public String name(HttpServletRequest request) throws Exception{
        BufferedReader br = new BufferedReader(new InputStreamReader(
                request.getInputStream(),"utf-8"
        ));
        Date date = new Date();
        String time = date.getTime()/1000 +"";
        //String media_id= "7QSvVNIVka6BRlW78G6LBqRsQWwg0odLB_WALoDjHiE";
        String str ;
        StringBuffer buffer = new StringBuffer();
        while ((str=br.readLine())!=null){
           buffer.append(str);
        }
        br.close();
        String xml = buffer.toString();
        int start =  xml.indexOf("CDATA[");
        int end = xml.indexOf("]",start);
        String toUserName = xml.substring(start+6,end);

         start =  xml.indexOf("CDATA[",end);
         end = xml.indexOf("]",start);
        String fromUserName = xml.substring(start+6,end);

        return "<xml>" +
                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>" +
                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>" +
                "  <CreateTime>"+time+"</CreateTime>" +
                "  <MsgType><![CDATA[text]]></MsgType>" +
                "  <Content><![CDATA[这是Zedis的测试信息!]]></Content>" +
                "</xml>";

//        return  "<xml>\n" +
//                "  <ToUserName><![CDATA["+fromUserName+"]]></ToUserName>\n" +
//                "  <FromUserName><![CDATA["+toUserName+"]]></FromUserName>\n" +
//                "  <CreateTime>"+time+"</CreateTime>\n" +
//                "  <MsgType><![CDATA[voice]]></MsgType>\n" +
//                "  <Voice>\n" +
//                "    <MediaId><![CDATA["+media_id+"]]></MediaId>\n" +
//                "  </Voice>\n" +
//                "</xml>";

    }




    @GetMapping("/index")
    public String name(String signature,String timestamp,String nonce,String echostr){
        String[] strs = { "acde", timestamp, nonce };
        Arrays.sort(strs);

        StringBuilder str = new StringBuilder();
        for (int i = 0; i < strs.length; i++) {
            str.append(strs[i]);
        }

        MessageDigest md = null;
        String tempStr = null;
        try
        {
            md = MessageDigest.getInstance("SHA-1");
            byte[] digest = md.digest(str.toString().getBytes());
            tempStr = byteToStr(digest);
        }
        catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }

        if (signature.toUpperCase().equals(tempStr)) {
            return echostr;
        }

        return "";
    }


    @GetMapping(path="/add")
    public @ResponseBody
    String addNewUser (@RequestParam String name
            , @RequestParam String content) {
        Todo todo = new Todo();
        todo.setContent("测试信息");
        todo.setCreatedate(new Date()+"");
        todo.setName("test1");
        todo.setId(1);
        todoDao.save(todo);
        return "Saved";
    }

    @GetMapping(path="/all")
    public @ResponseBody Iterable<Todo> getAllUsers() {

        return todoDao.findAll();
    }
    private String byteToStr(byte[] byteArray) {
        String strDigest = "";
        for (int i = 0; i < byteArray.length; i++) {
            strDigest = strDigest + byteToHexStr(byteArray[i]);
        }
        return strDigest;
    }

    private String byteToHexStr(byte b) {
        char[] digit = {
                '0',
                '1', '2', '3', '4', '5', '6', '7',
                '8', '9', 'A', 'B', 'C', 'D', 'E',
                'F' };

        char[] tempArr = new char[2];
        tempArr[0] = digit[(b >>> 4 & 0xF)];
        tempArr[1] = digit[(b & 0xF)];
        String s = new String(tempArr);
        return s;
    }


    @GetMapping("/find_openid")
    public String find_openid(String code){
        JSONObject obj = AccessTokenUtil.findWebAccessToken(code);
        return obj.getString("openid");
    }



}
